<?php
/*
  功能：题导入
  作者：cxm
  时间：2019-11-21
*/

namespace App\Excel;

use App\Models\QuestionImportRecord;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;

class QuestionImport implements ToCollection
{
    /**
     * 导入标题
     * @var int
     */
    protected $title;
    protected $originName;
    protected $fileName;
    public function __construct($title,$originName,$fileName)
    {
        $this->title = $title;
        $this->originName = $originName;
        $this->fileName = $fileName;
    }

    /**
     * 导入成功后处理
     * @param array $row
     *
     * @return User|null
     */
    public function collection(Collection $rows)
    {
        $name = 'question-'.uniqid();
        Log::info("导入文件处理---".$name);
        foreach ($rows as $key=>$item) {
            if ($key > 1) {
                // 插入数据，并且返回队列长度 （默认尾部插入）
                Redis::rpush($name, json_encode($item));
            }
        }
        $add = [
            'uuid'=> guid(),
            'lot' => $this->title,
            'excel_name' => $this->originName,
            'origin_filepath' => $this->fileName,
            'operation' => auth()->guard('admin')->user()->id,
            'redis_title'   => $name,
            'created_at'    => Carbon::now(),
            'updated_at'    => Carbon::now()
        ];
        QuestionImportRecord::insert($add);
        return true;//$rows->toArray();
    }
}